import Vue from 'vue'
import store from '@/store'
import LowAppMenuType from '../constant/LowAppMenuType'
import {LOW_APP_DEV_MODE} from '../constant/LowAppConst'
import {getMenuRouterLink, recursionMenuList} from '../utils/lowAppUtils'

// 动态注册 lowApp vuex缓存
store.registerModule('lowApp', {
  state: {
    // lowApp实体信息
    model: {},
    // lowApp菜单列表
    menuList: [],
    // 已初始化
    initialed: false,
    // 开发模式
    devMode: null,
  },
  mutations: {
    SET_LOW_APP_INFO: (state, info) => {
      state.model = info.record
      state.menuList = info.menuList
      state.initialed = true
    },
    SET_DEV_MODE: (state, flag) => state.devMode = flag,
  },
  actions: {
    setLowAppInfo: ({commit}, info) => {
      // 设置菜单的路由地址
      recursionMenuList(info.menuList, (menu, parent) => {
        if (menu.type !== LowAppMenuType.GROUP.type) {
          menu.routerLink = getMenuRouterLink(menu)
        }
      })
      commit('SET_LOW_APP_INFO', info)
    },
    // 设置 lowApp 的开发模式状态，通过 appId 隔离
    setLowAppDevMode({commit, state}, flag) {
      let appId = state.model.id
      if (!appId) {
        return false
      }
      Vue.ls.set(LOW_APP_DEV_MODE + appId, flag)
      commit('SET_DEV_MODE', flag)
    },
  },
  getters: {
    // 获取 lowApp 的开发模式状态，通过 appId 隔离
    getLowAppDevMode(state) {
      let devMode = state.devMode
      if (devMode == null) {
        devMode = false
        let appId = state.model.id
        if (appId) {
          devMode = getDevModeByLs(appId)
        }
        store.dispatch('setLowAppDevMode', devMode)
      }
      return devMode
    },
    getLowAppDevModeByLs: () => getDevModeByLs,
  },
})

/**
 * 通过appId在缓存里获取 devMode
 * @param appId
 * @return {boolean}
 */
function getDevModeByLs(appId) {
  let devMode = Vue.ls.get(LOW_APP_DEV_MODE + appId)
  if (typeof devMode !== 'boolean') {
    devMode = false
  }
  return devMode
}
